package neichuan.util.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

//读取默认配置文件
public class DefaultConfig {



    public static enum Field{
        BROWSER_SERVER_CONNECTION_COUNT("browser.server.connection.count"),//
        SERVER_PORT("server.port")
        ;
        private String value;
        Field(String value){
            this.value=value;
        }

        public String getValue() {
            return value;
        }
    }

    String path="/defaultConfig.properties";
    private static DefaultConfig defaultConfig;
    protected DefaultConfig(){

    }

    public static DefaultConfig getSimpleInstance(){
        if(defaultConfig ==null){
            synchronized (DefaultConfig.class){
                if(defaultConfig ==null){
                    defaultConfig =new UserConfig();
                }
            }
        }
        return defaultConfig;
    }

    private static Map<String,String> configMap;
    public synchronized void reset() throws IOException {
        configMap=new HashMap<>();
        Properties p=loadFile(path);
        loadPropertys(p);
    }

    /**
     *
     * @param path 相对路径
     * @return
     */
    protected Properties loadFile(String path) throws IOException {
        Properties p=new Properties();
        InputStream inputStream = DefaultConfig.class.getResourceAsStream(path);
        p.load(inputStream);
        return p;
    }

    protected Properties loadFile(InputStream inputStream) throws IOException {
        Properties p=new Properties();
        p.load(inputStream);
        return p;
    }

    protected void loadPropertys(Properties p){
        for(Field field:Field.values()){
            String key=field.value;
            String value=p.getProperty(key);
            if(value!=null && !value.equals("")){
                configMap.put(key,value);
            }
        }
    }

    public static String getConfig(String key){
        if(configMap==null){
            try {
                getSimpleInstance().reset();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return configMap.get(key);

    }

    public static String getConfig(Field key){
        return getConfig(key.value);
    }
}
